import { Vector2, Raycaster } from 'three';
import isAlpha from '../utils/isAlpha';

function createLoop(scene, camera, renderer, controls, labelRenderer, onClickFn, tickFn) {
	const animate = () => {
		Object.keys(tickFn).forEach((v) => {
			tickFn[v] && tickFn[v]();
		});
		renderer.setAnimationLoop(animate);
		controls.update();
		renderer.render(scene, camera);
		labelRenderer.render(scene, camera);
	};

	animate();

	window.addEventListener('resize', () => {
		camera.aspect = window.innerWidth / window.innerHeight;
		camera.updateProjectionMatrix();
		renderer.setSize(window.innerWidth, window.innerHeight);
		labelRenderer.setSize(window.innerWidth, window.innerHeight);
	});

	let intersect = null;
	window.addEventListener('pointerdown', (event) => {
		const mouse = new Vector2();
		mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
		mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

		const raycaster = new Raycaster();
		raycaster.setFromCamera(mouse, camera);

		if (raycaster) {
			const intersects = raycaster.intersectObjects(scene.children);

			// console.log(intersects);
			const targetBlock = intersects.find((item) => item.object.userData.isChangeColor);

			if (targetBlock){
			  onClickFn(targetBlock.object.parent.customProperties.adcode)
			}

			const target = intersects.filter((item) => item.object.type !== 'Line');
			if (target.length > 0) {
				if (target[0].object.type === 'Mesh') {
					if (intersect) isAlpha(intersect, 1);
					intersect = target[0].object.parent;
					isAlpha(intersect, 0.4);
				}
				if (target[0].object.type === 'Sprite') {
					// console.log(target[0].object);
				}
			} else {
				if (intersect) isAlpha(intersect, 1);
			}
		}
	});
}

export { createLoop };
